package com.example.kafkademo.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/kafka")
public class ProduceController {

    private static Logger logger = LoggerFactory.getLogger(ProduceController.class);

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping("send")
    public String sendKafka() {
        int messageNo = 1000;
        final int count = 2000;
        try {
            while (messageNo < count) {
                String key = String.valueOf(messageNo);
                String message = "hello kafka message " + key;
                kafkaTemplate.send("evan", key, message);
                System.out.println("发送的消息: " + message);
                messageNo++;
            }
            return "发送kafka成功";
        } catch (Exception e) {
            logger.error("发送kafka失败", e);
            return "发送kafka失败";
        }
    }
}
